package fyp.spedmew;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import fyp.spedmew.backend.entity.jobEndpoint.model.Job;
import fyp.spedmew.backend.entity.userEndpoint.model.User;
import fyp.spedmew.connector.JobListATask;
import fyp.spedmew.connector.UserFindByIdATask;

/**
 * Created by chengys on 17/12/2014.
 */
public class ListViewBaseActionBarActivity extends ActionBarActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    //protected RelativeLayout _completeLayout, _activityLayout;
    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    private ArrayList<NaviDrawerItemClass> navDrawerItems;
    private NaviDrawerListBaseAdapter adapter;

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout);
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items1);

        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons1);

        mTitle = mDrawerTitle = getTitle();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        if (getFragmentManager().findFragmentById(R.id.content_frame) == null) {
            ArrayListFragment list = new ArrayListFragment();
            getFragmentManager().beginTransaction().add(R.id.content_frame, list).commit();
        }

        navDrawerItems = new ArrayList<NaviDrawerItemClass>();

        // add nav drawer item
        if (navMenuIcons == null) {
            for (int i = 0; i < navMenuTitles.length; i++) {
                navDrawerItems.add(new NaviDrawerItemClass(navMenuTitles[i]));
            }
        } else {
            for (int i = 0; i < navMenuTitles.length; i++) {
                navDrawerItems.add(new NaviDrawerItemClass(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));
            }
        }

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // add navi drawer list adapter
        adapter = new NaviDrawerListBaseAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enable action bar app icon
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // actionbar description
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                //R.drawable.ic_drawer,
                R.string.app_name,

                R.string.app_name

        ) {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                supportInvalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                supportInvalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    public static class ArrayListFragment extends ListFragment {

        private List<ListViewClass> mItems;        // ListView items list

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // initialize the items list
            mItems = new ArrayList<ListViewClass>();
            Resources resources = getResources();


            try {
                List<Job> list;
                list = new JobListATask().execute().get();

                {
                    for (Job job : list) {
                        User dispatcher = new UserFindByIdATask().execute(job.getRecipientId()).get();
                        ListViewClass item = new ListViewClass();
                        item.setJobObject(job);
                        item.setTitle(job.getTitle());
                        item.setDescription(job.getDetail());
                        item.setName(dispatcher.getName());
                        item.setPrice("$ " + job.getPrice());
                        item.setIcon(resources.getDrawable(R.drawable.coffee));
                        item.setStatus_icon(resources.getDrawable(R.drawable.green));
                        item.setPic(job.getTitle());
                        item.setStatus("Status");
                        mItems.add(item);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (NullPointerException n){
                ListViewClass item = new ListViewClass();
            }

            // initialize and set the list adapter
            setListAdapter(new ListViewArrayAdapter(getActivity(), mItems));
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            // remove the dividers from the ListView of the ListFragment
            getListView().setDivider(null);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            ListViewClass item = mItems.get(position);
            User recipient = new User();
            try {
                recipient =  new UserFindByIdATask().execute(item.getJobObject().getRecipientId()).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            Bundle jobDetails=new Bundle();
            jobDetails.putString("name", item.getJobObject().getTitle());
            jobDetails.putString("descr", item.getJobObject().getDetail());
            jobDetails.putString("price", item.getJobObject().getPrice());
            jobDetails.putString("customIns",item.getJobObject().getInstruction());
            jobDetails.putString("recipientNo",recipient.getPhone());
            jobDetails.putString("pickupLoc",item.getJobObject().getPickupAddress().getLine1());
            jobDetails.putString("dropoffLoc", item.getJobObject().getDeliverAddress().getLine1());
            jobDetails.putString("date",item.getJobObject().getShipDate().toString());
            jobDetails.putString("id",item.getJobObject().getId().toString());

            Intent activity = new Intent(v.getContext(), DispatcherDetailActionBarActivity.class);
            activity.putExtras(jobDetails);
            startActivity(activity);



        }
    }

    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view selected item
            displayView(position);

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    // display fragment view of item
    public void displayView(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new JobListDispatcherListFragment();
                break;
            case 1:
                fragment = new JobReceivedListDispatcherListFragment();
                break;
            case 2:
                fragment = new JobsHistDispatcherListFragment();
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivityActionBarActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }



    // needed function for using ActionBarDrawerToggle
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}


